package com.lanju.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.lanju.common.WxMessageUtil;
import com.lanju.dao.AppointmentDao;
import com.lanju.dao.HouseDao;
import com.lanju.dao.SMSCaptchaDao;
import com.lanju.dao.UserDao;
import com.lanju.entity.Appointment;
import com.lanju.entity.House;
import com.lanju.entity.User;
import com.lanju.model.ResultModel;
import com.lanju.service.AppointmentService;


@Service
public class AppointmentServiceImpl implements AppointmentService{

    private static final Logger LOGGER = LoggerFactory.getLogger(AppointmentServiceImpl.class);
    
    @Autowired
    AppointmentDao appointmentDao;
    @Autowired
    SMSCaptchaDao sMSCaptchaDao;
    
	@Autowired 
	private UserDao userDao;
	
	@Autowired
	HouseDao houseDao;
	

    /** 新增 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel add(Appointment appointment,HttpServletRequest request, HttpServletResponse response) {
        try {
        	appointmentDao.persist(appointment);
        	House h=houseDao.findById(appointment.getHouseId());
        	Map<String,Object> map =new HashMap<>();
        	map.put("reviceType", "租房预约提醒");
			List<User> ulist=userDao.getSendMessageUser(map);
			String templateId  ="Ukw3HWIx9QsXaoEq6riXFfJMw2MPezAMn3Bucbw7t-8";
			Integer count=0;
			System.out.println(appointment.getAppointmentTime());
			if(ulist != null && ulist.size()>0){
				for(int i=0;i<ulist.size();i++){
					User u_=ulist.get(i);
					if(!StringUtils.isEmpty(u_.getOpenId())){
						String data="{\"touser\":\""+u_.getOpenId()+"\",\"template_id\":\""+templateId+"\",\"topcolor\":\"#FF0000\", "
								+ "\"data\":{\"first\": { \"value\":\""+"看房预约提醒信息"+"\",\"color\":\"#173177\"},"
										+ "\"keyword1\":{\"value\":\""+"看房预约"+"\",\"color\":\"#173177\" },"
												+ "\"keyword2\": { \"value\":\""+(appointment.getNickName()+"("+appointment.getPhone())+")\",\"color\":\"#173177\"},"
														+ "\"keyword3\":{\"value\":\""+"看房服务"+"\",\"color\":\"#173177\"}, "
														+ "\"keyword4\":{\"value\":\""+"待受理 "+"\",\"color\":\"#173177\"}, "
														+ "\"keyword5\":{\"value\":\""+h.getHouseName()+"\",\"color\":\"#173177\"}, "
																+ "\"remark\":{\"value\":\""+"看房时间是："+appointment.getAppointmentTime()+"请尽快联系客户"+"\",\"color\":\"#173177\"}"
																		+ "}}";
						synchronized (data) {
							WxMessageUtil.sendcontractPayMessage(request, response, data);
							count ++;
						}
					}	
				}
			}

			System.out.println("总共发送给"+count+"个管理员");
            return ResultModel.success("录入成功", "总共发送给"+count+"个管理员");
        } catch (Exception e) {
            LOGGER.error("addAppointment fail",e);
        }
        return ResultModel.fail("录入失败", null);
    }

    /** 根据id删除 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel del(Appointment appointment) {
    	String appointmentId = appointment.getAppointmentId();
        Appointment obj = appointmentDao.getById(appointmentId);
        if(obj==null){
            return ResultModel.fail("Appointment不存在", null);
        }
        try {
            appointmentDao.remove(appointment);;
            return ResultModel.success("删除成功", null);
        } catch (Exception e) {
            LOGGER.error("delAppointment fail",e);
        }
        return ResultModel.fail("删除失败", null);
    }
    
    
    /** 根据id修改 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel edit(Appointment appointment) {
        Appointment obj = appointmentDao.getById(appointment.getAppointmentId());
        if(obj==null){
            return ResultModel.fail("Appointment不存在", null);
        }
        try {
            appointmentDao.merge(appointment);
            return ResultModel.success("编辑成功", null);
        } catch (Exception e) {
            LOGGER.error("editAppointment fail",e);
        }
        return ResultModel.fail("编辑失败", null);
    }

    /** 根据id获取 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Appointment getById(String id) {
        Appointment obj = appointmentDao.getById(id);
        return obj;
    }
    
    /** 根据参数获取 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Appointment getByParam(Appointment appointment) {
        Appointment obj = appointmentDao.getByParam(appointment);
        return obj;
    }
    
    

    /** 分页查询 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Map<String, Object> getList(Map param, int pageSize, int offset) {
    	 Map<String, Object> rsMap = new HashMap<String, Object>();
    	 long count = appointmentDao.getListCount(param);
         List<Map> list = appointmentDao.getList(param, pageSize, offset);
         rsMap.put("total", count);
         rsMap.put("rows", list);
        return rsMap;
    }

	@Override
	@Transactional
	public Map<String, Object> delAppointment(String id) {
		Map<String, Object> result=new HashMap<>();
		try {
			appointmentDao.delAppointment(id);
			result.put("success", true);
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
		}
		return result;
	}
    
  
}
